×
☰ See All Chapters

Spring Data JPA Repositories

There are 3 repository interfaces that you should know when you use Spring Data JPA:

  1. CrudRepository 

  2. PagingAndSortingRepository 

  3. JpaRepository 

The below picture shows the hierarch of these three repositories.

                                                                  spring-data-jpa-repositories-0
 
  • Repository interface is a marker interface and the super interface of all Spring Data Repository. It takes the domain/Entity class to manage as well as the id type of the domain/Entity class as type arguments. 

  • The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed. 

  • On top of the CrudRepository there is a PagingAndSortingRepository abstraction that adds additional methods to ease paginated access to entities. 

  • JpaRepository provides JPA specific abstractions. JpaRepository extends PagingAndSortingRepository and expose the capabilities of the underlying persistence technology in addition to the rather generic persistence technology-agnostic interfaces like e.g. CrudRepository. JpaRepository combines the methods declared by the PagingAndSortingRepository and CrudRepository repository interfaces. 

How to use spring data JPA repositories

  1. Create a repository interface and extend one of the repository interfaces provided by Spring Data. 

public interface  StudentRepository extends CrudRepository<Student, Long>{

}

We should pass the Entity type and the id type as the type parameters. We have used Student entity class and the data type of id field in Student classis the Long.

public class Test {

@Entity

public class Student {

 

        @Id

        @GeneratedValue(strategy = GenerationType.IDENTITY)

        private Long id;

        private String firstName;

        private String lastName;

 

        public Student() {

                super();

        }

       

        public Student(String firstName, String lastName) {

                super();

                this.firstName = firstName;

                this.lastName = lastName;

        }

       

        //Setters and getters

}

 

 

  1. Instantiate and use Repository: To instantiate our StudentRepository that has extended CrudRepository, we can use dependency injection. We never create the implementation class for repository. Spring Data JPA provided the implementation and we should use that by injecting. 

@Service("studentService")

public class StudentService {

        @Autowired

        private StudentRepository repository;

       

        public void test() {

                // Save a new student

                Student student = new Student("Manu", "Manjunatha");

                repository.save(student);

        }

}

 


All Chapters
Author